#include <flache_rsync.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <errno.h>
#include <flache_debug.h>

int strcount( char* s, char c )
{
    int count = 0;
    int i;
    for( i = 0; i < strlen( s ); i++ )
        if ( s[i] == c )
            count++;
    //char out[500];
    //sprintf(out, "count: %s: %d", s, count );
    //write_output( out );
    return count;
}

int create_path(char *orig_path)
{
    char *sep = "/";
    char *word, *brkt;
    struct stat st;
    int result = 0;

    char* path = (char*)malloc( strlen(orig_path) + 1 );
    strcpy( path, orig_path );

    printf("%s\n",path);
    
    

    char* cur_folder = (char*)malloc(strlen(path) + 1);
    memset( cur_folder, 0, strlen(path) + 1 );
    
    int count = strcount( path, sep[0] );
    int i = 0;
    for (word = strtok_r(path, sep, &brkt); word && result == 0 && i < count - 1; word = strtok_r(NULL, sep, &brkt))
    {
        char* temp = (char*)malloc(strlen(word) + strlen(sep) + 1);
        strcpy(temp, sep);
        strcat(temp, word);
        strcat(cur_folder, temp);
            
        if(stat(cur_folder,&st) != 0)
        {
            char* mkdir = "mkdir ";
            char* cmd = (char*)malloc( strlen( mkdir ) + strlen( cur_folder ) + 3 );
            sprintf( cmd, "%s\"%s\"", mkdir, cur_folder );
            result = system( cmd );
            free( cmd );

            // breaks if failed to create path
        }
        free(temp);
        i++;
    }
    free(cur_folder);
    free(path);
    return result;
}

int perform_rsync(char *path_from, char *path_to, int recursive)
{
    char cmd[34];
    char* trailing_slash = "";
    int ret = 0;
    ret = create_path(path_to);
    if( ret != 0)
        return ret;  //path does not exist and could not be created
    
    if(recursive)
    {
        strcpy(cmd,"rsync --stats --times --perms -r ");
        trailing_slash = "/";
    }
    else
        strcpy(cmd,"rsync --stats --times --perms -d ");
    
    //char full_path[strlen(path_to) + strlen(path_from) + 4];
    //sprintf( full_path, "%s %s", path_from, path_to );

    char full_cmd[strlen(cmd) + strlen(path_from) + strlen(path_to) + 8];
    sprintf( full_cmd, "%s \"%s%s\" \"%s\"", cmd, path_from, trailing_slash, path_to );
    
    ret = system(full_cmd);
    if ( 5888 == ret )
        ret = EREMOTEIO; /* Remote I/O error */

    write_output2( "perform_rsync: ", full_cmd );
    report_error( "rsync result: ", ret );
    return ret;
}

